<template>
    <div class="mx-auto bg-gray-50 ">
      <!-- 创建试卷 -->
      <div v-if="isSelect" class="mb-10">
        <!-- 试卷的基本设置 -->
        <div class="px-4 py-6 bg-white">
            <span  class="font-bold">新建试卷202507170624</span>
            <el-form class="mt-4 ">
                <el-form-item >
                    <template #label>
                        <span class="font-bold">题目序号</span>
                    </template>
                    <el-radio-group v-model="headerForm.numbering" class="ml-2">
                        <el-radio label="连续编号" value="serial"></el-radio>    
                        <el-radio label="按题型编号" value="questionType" :disabled="headerForm.byTypeClassify=='0'"></el-radio>    
                    </el-radio-group>
                </el-form-item>
                <el-form-item >
                     <template #label>
                        <span class="font-bold">题型设置</span>
                    </template>
                    <el-radio-group v-model="headerForm.byTypeClassify" class="ml-2">
                        <el-radio label="按照题型归类" value='1'></el-radio>    
                        <el-radio label="不按题型归类" value='0'  :disabled="headerForm.numbering=='questionType'"></el-radio>    
                    </el-radio-group>
                </el-form-item>
                <el-form-item >
                    <template #label>
                        <span class="font-bold">试卷难度</span>
                    </template>
                    <el-select v-model="headerForm.difficulty" placeholder="请选择难度" class="ml-2.5 w-40 rounded-lg">
                        <el-option label="简单" value="simple"></el-option>
                        <el-option label="中等" value="medium"></el-option>
                        <el-option label="困难" value="hard"></el-option>
                    </el-select>    
                </el-form-item>
            </el-form>
            <el-button type="primary" link :icon="Plus">新建分卷</el-button>
        </div>
        <!-- 试卷创建部分 -->
         <div class="flex gap-6  mt-6">
            <!-- 题目导航 -->
            <div class="bg-white  w-[20%] rounded-lg overflow-auto px-2">
                <!-- 设置分数 -->
                <div class="flex justify-between items-center p-4" v-show="!isBatchSettings">
                    <div class="text-gray-400 flex items-center gap-2">
                         <span>题量0,</span>
                        <span>总分0.0</span>
                    </div>
                    <el-button type="primary" link :icon="Plus" @click="batchSettings">批量设置</el-button>  
                </div>
                <div class="flex justify-between items-center p-4" v-show="isBatchSettings">
                    <el-button  round class="text-blue-400" @click="batchSettingsDialogVisible=true">设置分值</el-button>
                    <el-button link  type="info" @click="isBatchSettings=false"><FontAwesomeIcon icon="fa-solid fa-power-off" class="mr-1"/>  退出设置</el-button>  
                </div>
                <!-- 题目列表区域 -->
                 <div class="">
                    <div v-for="(item,index1) in paperQuestions" :key="item.questionType" class="space-y-4 mb-4 p-2">
                      
                        <div class="flex items-center  space-x-8">
                          <div class="flex items-center space-x-2">
                            <el-checkbox v-if="isBatchSettings" v-model="item.isChecked"  @change="handleCheckedChange(item,index1)"/>
                            <span class="text-sm font-bold  text-gray-700/90 whitespace-nowrap">
                                <b v-if="index1 === 0">一、</b>
                                <b v-if="index1 === 1">二、</b>
                                <b v-if="index1 === 2">四、</b>
                                <b v-if="index1 === 3">五、</b>
                                <b v-if="index1 === 4">六、</b>
                                {{ item.questionType }}(共{{ item.count }}题，{{ item.totalScore }} 分)
                            </span>
                            </div>
                            <div class="flex items-center space-x-3 px-2">
                                <el-icon class="text-sm  text-gray-400 hover:text-blue-400 rotate-45"><Menu /></el-icon>
                                <font-awesome-icon icon="far fa-trash-can" class="text-sm  text-gray-400 hover:text-blue-400" @click="byTypeDeleteQuestions(index1)"></font-awesome-icon>
                                <font-awesome-icon icon="fas fa-ellipsis-h" class="text-sm  text-gray-400 hover:text-blue-400 fa-rotate-90"></font-awesome-icon>
                            </div>
                        </div>
                        <div class=" text-gray-500  text-[12px] hover:text-[#409eff] cursor-pointer "  @click="handleDesc(item,index1)">
                            <el-icon class="mr-2" size="small"><EditPen /></el-icon>
                            <span>{{ item.desc }}</span>
                        </div>   
                        <!-- 遍历题目 -->
                        <div v-for="(question, index2) in item.questionList" :key="index2"  
                          :class="['flex  items-center  p-1 cursor-pointer',clickSelectedQuestionId === question.questionId? 'bg-sky-100 text-blue-500' : 'hover:bg-gray-100']"  >
                            <div class="flex items-center space-x-2  text-gray-500 w-[70%] " 
                             @click="handleClickQuestion(question,index1,index2)">    
                              <el-checkbox  v-if="isBatchSettings" v-model="question.isChecked" @change="handleCheckedChange(question,index1, index2,$event)" />
                              <div class=" flex items-center w-[70%]">
                                <span v-if="headerForm.numbering=='serial'">{{ question.questionNumber }} </span> 
                                <span v-else>{{ index2+1 }} </span>
                                 <span class="whitespace-nowrap"> ({{ question.questionScore }}分) </span>
                                  <div class="text-sm html-truncate  " v-html="question.questionContent"></div>
                                  <!-- <div class="text-sm truncate md:line-clamp-2" >{{ question.questionContent }} </div> -->
                                  <!-- {{ question.questionContent }}  -->
                              </div>
                            </div>  
                            <div class="flex items-center space-x-4 px-2">
                                <el-icon class="text-sm  text-gray-400 hover:text-blue-400 rotate-45"><Menu /></el-icon>
                                <font-awesome-icon icon="far fa-trash-can" class="text-sm  text-gray-400 hover:text-blue-400"  @click="handleDeleteQuestion('left',question,index1,index2)"></font-awesome-icon>
                            </div>
                        </div>
                    </div>
                 </div>

            </div>
            <!-- 创建题目区域 -->
             <div class="  w-[80%]">
                <!-- 添加题目的按钮 -->
                <div class="h-[60px] px-4 py-6  bg-white mb-6 rounded-lg flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <div class="flex items-center  text-gray-400 space-x-6">
                            <span class="text-base">添加题目 </span>
                            <div class="relative">
                            <el-tooltip effect="dark"placement="top-start" >
                                <template #content>新建题目会默认保存到题库，在此处编辑并<br>保存内容将同步修改题库对应题目 </template>
                                <el-icon class="text-gray-400/80 absolute  top-[-8px]  right-[2px]" size="large"><InfoFilled/></el-icon>
                            </el-tooltip>
                            </div>
                        </div>
                        <div>
                            <el-button round class="w-20" v-for="(item,index) in questionTypeList" :key="index" @click="changeQuestionType(item)">{{item}}</el-button>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <el-button type="primary" link>智能导入</el-button>
                        <el-dropdown trigger="hover" class="mx-4 ">
                            <el-button  type="primary" link>选题</el-button>
                            <template #dropdown>
                            <el-dropdown-menu class="import-dropdown">
                                <el-dropdown-item @click="handleSelectQuestion('questionBank')">从题库选题</el-dropdown-item>
                                <el-dropdown-item @click="handleSelectQuestion('cloud')">从云盘选题</el-dropdown-item>
                                <el-dropdown-item @click="handleSelectQuestion('ai')">Ai出题</el-dropdown-item>
                            </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        
                    </div>
                </div>
                <!-- 题目的预览 -->
                 <div v-if="isReview" class="bg-white rounded-xl p-6 shadow-sm hover:border hover:border-dotted  hover:border-blue-400 relative" 
                  @mouseenter="isShowReviewBtn=true" @mouseleave="isShowReviewBtn=false">
                  <div class="flex justify-end absolute top-0 right-0" v-show="isShowReviewBtn">
                    <button class=" flex items-center  justify-center bg-blue-500 text-white h-8  px-4 rounded-bl-lg hover:bg-blue-300" @click="handleEditQuestion">编辑</button>
                    <button class=" flex items-center  justify-center bg-blue-500 text-white h-8  px-4 hover:bg-blue-300">换一题</button>
                     <div class=" flex items-center  justify-center cursor-pointer bg-blue-100 w-10 h-8  rounded-tr-lg" @click="handleDeleteQuestion('rightReview')">
                          <el-icon ><Delete /></el-icon>
                      </div>
                  </div>
                   <QueReviewComponent :questionDetail="clickSelectedQuestion" :from="'试卷'" />
                </div>
                <div v-else>
                  <div class="mt-6 bg-white px-4 py-6 rounded-lg h-[800px] flex items-center justify-center" v-if="currentType==''">
                        <span class="text-gray-400  ">点击题型按钮添加题目</span>
                  </div>
                  <!-- 题目预览 -->
                  <div class="mt-6 bg-white px-4 py-6 rounded-lg  border border-blue-400 relative" v-else>
                      <div class="absolute top-0 right-0 flex items-center  justify-center cursor-pointer bg-blue-200 w-10 h-8 rounded-bl-lg rounded-tr-lg" @click="handleDeleteQuestion('right')">
                          <el-icon ><Delete /></el-icon>
                      </div>
                    
                      <CreateQuestionMain :currentType="currentType"  :mode="mode"  :questionNumber="currentQuestionNumber" v-model:questionData="addingQuestion" 
                      v-model:isSave="isSave"/>           
                  </div>
                </div>  
             </div>
         </div>
      </div>
      <!-- 从题库中选题 -->
       <Question 
          :source="'paper'"
          v-model:isSelect="isSelect" 
          v-model:selectedQuestions="selectedQuestions" 
          :selectedIds="currentPaperQuestionIds" v-else/> 
       
      <el-affix position="bottom" :offset="10" v-if="isSelect">
        <div class=" bg-[#384B66] flex justify-end rounded">
            <el-button type="primary"  class="w-20 rounded">完成</el-button>
        </div>
      </el-affix>

         <!-- 批量设置分值的模态框 -->
    <el-dialog v-model="batchSettingsDialogVisible" title="修改难度"  width="20%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              批量设置分值
            </span>    
          </div>
        </template>
        <div v-if="checkedQuestionCount==0">
          已选 <b class="text-blue-400">0</b> 题,将所选题目
          <el-select v-model="batchSettingScoreData.settingScore" class="ml-2.5 w-40 rounded-lg">
              <el-option label="按题设分" value="byItem"></el-option>
              <el-option label="按空设分" value="byGap"></el-option>
          </el-select> ,每题分值为
          <el-input v-model="batchSettingScoreData.score" class="w-20 rounded-lg"></el-input>
          分
        </div>
        <div v-else>
          已选 <b class="text-blue-400">{{ checkedQuestionCount }}</b> 题,将所选题目的分值设为
          <el-input v-model.number.trim="batchSettingScoreData.score" class="w-20 rounded-lg"></el-input>
          分
        </div>
       
      <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="batchSettingsDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="batchSettingScore" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
         <!-- 题型说明的模态框 -->
    <el-dialog v-model="typeDescriptionDialogVisible" title="修改难度"  width="20%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              题型说明
            </span>    
          </div>
        </template>
       <el-input  v-model="typeDescription" type="textarea" placeholder="请输入题型说明" class="w-full"/>
      <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="typeDescriptionDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="updateQuestionTypeDesc" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
    <!--删除的模态框 -->
    <el-dialog v-model="deleteQuestionDialogVisible" title="提示"  width="20%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              提示
            </span>    
          </div>
        </template>
        <div>
            你确定删除吗?删除该道小题以后,你的试卷将不会出现该题目！
        </div>
        <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="deleteQuestionDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="confirmDeleteQuestion" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
    <!--删除的模态框 -->
    <el-dialog v-model="deleteTypeDialogVisible" title="提示"  width="20%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header border-b pb-4">
            <span :id="titleId" :class="titleClass">
              提示
            </span>    
          </div>
        </template>
        <div>
            你确定删除吗?如果你删除大题将同时删除了该题型下面所有的小题！
        </div>
        <template #footer>
          <div class="py-4 px-6 border-t flex items-center justify-end">
            <div class="flex gap-4">
              <el-button @click="deleteTypeDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="confirmDeleteTypeQuestions" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive,watch,computed,onMounted} from "vue";
import { Plus,InfoFilled,EditPen,Menu } from '@element-plus/icons-vue'
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import CreateQuestionMain from "../CreateQuestionMain.vue";
import QueReviewComponent from "@/views/exam/QueReviewComponent.vue";
import Question from '@/views/exam/Question.vue';
import {useEditPaperStore} from "@/store/editPaper"
import {getPaperAllContent} from "@/api/exam.js"
const editPaperStore = useEditPaperStore()
console.log(editPaperStore.paperId,'editPaperStore');
onMounted(()=>{
  if(editPaperStore.paperId){//编辑试卷
    //根据试卷id查询
    getPaperAllContent(editPaperStore.paperId).then((res)=>{
        console.log(res,'res');
        paperQuestions.value =res.data.data
    })
  }
})
//表单选项
const headerForm = reactive({
    numbering: 'serial',
    byTypeClassify: '1',
    difficulty: "simple"
});
const  questionTypeList = ref(['单选题','多选题','填空题','判断题','简答题','更多']);
const currentType = ref('');
const  mode = ref('创建试卷');
const  batchSettingScoreData = reactive({
    //被选择题目数量
    number: 0,
    //设置分数的方式
    settingScore: "byItem",
    //每题分值
    score: null
})

//批量设置
const  isBatchSettings = ref(false);
const  batchSettings = () => {
    console.log("批量设置")
    isBatchSettings.value = true;
}
// 批量设置的模态框
const batchSettingsDialogVisible = ref(false);
// 批量设置确定按钮
const  batchSettingScore = () => { 
  batchSettingScoreData.number = checkedQuestionCount.value
  batchSettingScoreData.checkedQuestionIds = checkedQuestionIds.value
    console.log("批量设置确定按钮",batchSettingScoreData)
    //修改所有被选择题目的分数
    checkedQuestionIds.value.forEach((questionId) => {
        paperQuestions.value.forEach((item) => {
           item.questionList.forEach((question) => {
            if (question.questionId === questionId) {
              question.questionScore = batchSettingScoreData.score
            }
          })
        });
    }) 
    console.log(paperQuestions.value,'paperQuestions.value');
    //计算每个类别题目的中分 
    paperQuestions.value.forEach((item) => { 
        item.totalScore = item.questionList.reduce((pre, cur) => {
            return pre + cur.questionScore;
        }, 0);
    })
    //todo 调用后台修改题目的分值

    batchSettingsDialogVisible.value = false;



};


//定义左侧题目列表要展示的数据
const  paperQuestions = ref([
    {  
        questionType: '单选题', questionScore: 5,totalScore:0,desc:'题型说明',
        questionList:[
            // {  questionId:1, questionContent:'内存管理中，将暂时不用的进程移出内存到磁盘，需要时再载入的技术是( )',questionScore:5,questionDifficulty:"简单",questionType:'单选题'},
            // {  questionId:2, questionContent:'内存管理中，将暂时不用的进程移出内存到磁盘，需要时再载入的技术是( )',questionScore:5,questionDifficulty:"简单",questionType:'单选题'},
            // {  questionId:3, questionContent:'内存管理中，将暂时不用的进程移出内存到磁盘，需要时再载入的技术是( )',questionScore:5,questionDifficulty:"简单",questionType:'单选题'},
        ],
        count:0 
},
    {  questionType: '多选题', questionScore: 5,totalScore:0,desc:'题型说明',questionList:[],count:0 },
    {  questionType: '填空题', questionScore: 5,totalScore:0,desc:'题型说明',questionList:[],count:0 },
    {  questionType: '判断题', questionScore: 5,totalScore:0,desc:'题型说明',questionList:[],count:0 },
    {  questionType: '简答题', questionScore: 5,totalScore:0,desc:'题型说明',questionList:[],count:0 },
]);
//分数设置的是否题目选中状态发生改变时触发的事件函数
const  handleCheckedChange = (item,index1, index2) => { 
  console.log(item,index1,index2);
  //修该题目类型
  if(index2>=0){//index2不为空，说明是题目级别的选中状态改变
    console.log('修改题的选中状态11');
    //改题目中的选中状态为false 对应题目组级别的选中状态为false
    if(!item.isChecked){
      paperQuestions.value[index1].isChecked = false;
    }else{
      // 如果选中题目的状态为true  测检测题组中的所有题目是否都为选中状态 如果是，则题目组选中状态为true
      let isAllChecked = true;
      for(let i = 0; i < paperQuestions.value[index1].questionList.length; i++){ 
        if(!paperQuestions.value[index1].questionList[i].isChecked){
          isAllChecked = false;
          break;
        }
      }
      paperQuestions.value[index1].isChecked = isAllChecked;
    }

  }else{//index2为空，说明是题目组级别的选中状态改变
    console.log('修改题组选中状态22');
    if(item.isChecked){//题目组选中
      item.questionList.forEach((question) => { 
        question.isChecked = true;
      });
    }else{//题目组取消选中
      item.questionList.forEach((question) => { 
        question.isChecked = false;
      });
    }
    
  }
}
//被选中的额题目数量
const checkedQuestionCount = computed(() => {
  let count = 0;
  paperQuestions.value.forEach((item) => {
    item.questionList.forEach((question) => {
      if (question.isChecked) {
        count++;
      }
    });
  });
  return count;
});
// 所有被选择修改分支的题目的id 
const checkedQuestionIds = computed(() => {
  let ids = [];
  paperQuestions.value.forEach((item) => {
    item.questionList.forEach((question) => {
      if (question.isChecked) {
        ids.push(question.questionId);
      }
    });
  });
  return ids;
});
// 点击创建题对应的题目 创建完成之后加入到试卷中
// 题目序号
const questionNumber = ref(1);
//当前题目序号
const  currentQuestionNumber = ref(1);
const addQuestion = (type, defaultScore = 5) => {
  // 1. 检查题型分类是否存在，不存在则创建
  if (!paperQuestions.value.some(item => item.questionType === type)) {
    paperQuestions.value.push({
      questionType: type,
      questionScore: defaultScore,
      totalScore: 0,
      desc: '',
      questionList: [],
      count: 0
    });
  }

  // 2. 获取题型分类下标
  const index = paperQuestions.value.findIndex(item => item.questionType === type);
  
  // 3. 添加题目到分类
  const newQuestion = {
    questionId: new Date().getTime(), // 使用时间戳作为题目ID
    questionContent: '',
    questionScore: defaultScore,
    difficulty: "0.8",
    questionType: type,
    questionNumber: questionNumber.value, // 初始使用当前计数器值
    currentQuestionNumber:questionNumber.value, // 使用当前计数器值，并在每次调用时递增
  };
  
  paperQuestions.value[index].questionList.push(newQuestion);

  // 4. 更新分类计数
  paperQuestions.value[index].count++;
  paperQuestions.value[index].totalScore += defaultScore;
    // 返回新添加的题目对象
  return newQuestion;
};
// 重新计算所有题目的序号，并返回最后一个题目的序号
const renumberAllQuestions = () => {
  let questionCount = 1;
  
  // 遍历所有题型分组
  paperQuestions.value.forEach(group => {
    // 遍历当前题型分组内的所有题目
    group.questionList.forEach(question => {
      // 更新题目序号
      question.questionNumber = questionCount;
      questionCount++;
    });
  });
  
  // 更新全局题目计数器
  questionNumber.value = questionCount;
  
  // 返回最后一个题目的序号（即最新添加题目的序号）
  return questionCount - 1;
};


const changeQuestionType = (type) => {
  console.log("点击按钮创建题目==>", type);
  currentType.value = type;
  isSave.value =false
  isReview.value =false

  addingQuestion.value={}
  let newQuestion = null;

  switch (type) {
    case '单选题':
      newQuestion = addQuestion(type);
      break;
    case '多选题':
      newQuestion = addQuestion(type);
      break;
    case '填空题':
      newQuestion = addQuestion(type, 8); 
      break;
    case '简答题':
      newQuestion = addQuestion(type, 10);
      break;
    case '判断题':
      newQuestion = addQuestion(type);
      break;
    case '编程题':
      newQuestion = addQuestion(type, 15);
      break;
    case 'Audio':
      newQuestion = addQuestion(type, 6);
      break;
  }
 // 添加题目后重新编号所有题目
  currentQuestionNumber.value = renumberAllQuestions();
  // clickSelectedQuestionNumber.value=currentQuestionNumber.value; // 更新当前选中的题目序号

  
  // 记录当前添加的题目序号（新添加题目的实际序号）
  console.log(`新添加的题目序号: ${currentQuestionNumber.value}`,paperQuestions.value);
}


// 题型说明 
const  typeDescriptionDialogVisible = ref(false);
const typeDescription = ref('');

const  handleDesc=(item,index)=>{
    typeDescriptionDialogVisible.value=true
    console.log(item,index)
}
// 修改题型说明
const updateQuestionTypeDesc = () => {
    console.log("修改题型说明")
};

/*****************删除题目************* */
const  deleteQuestionDialogVisible = ref(false);
const  deleteQuestionData = ref({});
const  deleteQuestionIndex = ref(0);
const deleteQuestionTypeIndex = ref(0);
const  deleteDirection=ref(null)
//右侧题目预览区域的删除按钮点击事件
const  handleDeleteQuestion = (direction,item,index1,index2) => {
    console.log("删除题目",direction,item,index1,index2)
    deleteQuestionData.value = item;
    deleteQuestionTypeIndex.value=index1;
    deleteQuestionIndex.value = index2;
    deleteDirection.value=direction;
    deleteQuestionDialogVisible.value=true
};

const  confirmDeleteQuestion = (val) => { 
    console.log("删除题目")
    // 右侧删除 
    if(deleteDirection.value=='right'){
      let  outIndex = null
      let  flag = false
      //根据题目序号删除
      paperQuestions.value.forEach((item,index1)=>{ 
        item.questionList.forEach((question,index2)=>{ 
          if(question.currentQuestionNumber==currentQuestionNumber.value){
            item.questionList.splice(index2,1)
            flag = true
             //当前类型中是删除了题目
            outIndex = index1
          }
        })
        
      })
      if(flag){  //当前类型中删除了题目
          if(paperQuestions.value[outIndex].questionList.length==0){  //当前类型中没有题目
            paperQuestions.value.splice(outIndex,1)
          }
        }

    }else if(deleteDirection.value=='left'){  // 左侧删除
        paperQuestions.value[deleteQuestionTypeIndex.value].questionList.splice(deleteQuestionIndex.value,1)
        if(paperQuestions.value[deleteQuestionTypeIndex.value].questionList.length==0){  //当前类型中没有题目
          paperQuestions.value.splice(deleteQuestionTypeIndex.value,1)
        }    
    }else if(deleteDirection.value=='rightReview'){  // 右侧预览题目中的删除 
      console.log("预览的题目删除",clickSelectedQuestion.value);
      //找到预览题目的索引
      let deleteQuestionIndex1 = null;//要删除的题目的索引
      let deleteTypeIndex = null;//要删除题目类型的索引
      paperQuestions.value.forEach((item,index1)=>{ 
        item.questionList.forEach((question,index2)=>{ 
          if(clickSelectedQuestion.value.currentQuestionNumber==question.currentQuestionNumber){  //找到预览题目的索引
            deleteQuestionIndex1 = index2
            deleteTypeIndex = index1
            return true
          }
        })
      })
      paperQuestions.value[deleteTypeIndex].questionList.splice(deleteQuestionIndex1,1)
      if(paperQuestions.value[deleteTypeIndex].questionList.length==0){  //当前类型中没有题目
        paperQuestions.value.splice(deleteTypeIndex,1)}
        clickSelectedQuestion.value = paperQuestions.value[0].questionList[0]; // 预览的题目编程下一个类目中的第一个
      }else{  //当前类目中还有题目
        clickSelectedQuestion.value = paperQuestions.value[deleteTypeIndex].questionList[0]; // 预览的题目编程下一个类目中的第一个
      }

     currentType.value='' // 清空当前类型
      deleteQuestionDialogVisible.value=false
      // 重新编号所有题目
      renumberAllQuestions()
};
//左侧删除某一类型的题目
const  deleteTypeIndex =ref('') 
const  deleteTypeDialogVisible = ref(false)
const byTypeDeleteQuestions = (index) => { 
  deleteTypeIndex.value = index
  deleteTypeDialogVisible.value=true

};
const confirmDeleteTypeQuestions = () => { 
  paperQuestions.value.splice(deleteTypeIndex.value,1)
  deleteTypeDialogVisible.value=false
  currentType.value='' // 清空当前类型
  renumberAllQuestions()

};


const addingQuestion = ref({})
const isSave=ref(false)
// 监听题目编辑区域是否点击了保存按钮
watch(()=>isSave.value,(newVal)=>{
  console.log(111,addingQuestion.value,newVal);
  if(newVal){ 
     // 保存题目
     paperQuestions.value.forEach(item=>{
      item.questionList.forEach(item=>{
        if(item.currentQuestionNumber==currentQuestionNumber.value){
          item.questionContent=addingQuestion.value.questionContent
          //  item.questionId=addingQuestion.value.id
           item.questionDifficulty=addingQuestion.value.difficulty 
           item.questionType=addingQuestion.value.questionType
           item.knowledgePoints=addingQuestion.value.knowledgePoints
           item.tags=addingQuestion.value.tags
           item.answer=addingQuestion.value.answer
           item.options=addingQuestion.value.options
           item.analysis=addingQuestion.value.analysis
            clickSelectedQuestion.value = item
           return
        }
      })
     })
   // 确认题目保存后 预览题目
    isReview.value=true
   
  }else{
    isReview.value=false
  }
})


// 右侧题目被点击的事件
// 被点击选中的题目 
const   clickSelectedQuestion = ref({})
// 被点击选中的题目序号
const  clickSelectedQuestionId = ref(0)
// 被点击选中的题目类型索引
const  clickSelectedQuestionTypeIndex = ref(0)
const  isReview = ref(false)
//是否显示预览部分的操作按钮
const  isShowReviewBtn=ref(false)
const handleClickQuestion=(item,index1,index2) => { 
  console.log(item,'题目被点击',index1,index2);
  clickSelectedQuestion.value=item
  isReview.value=true
  clickSelectedQuestionId.value=item.questionId
  clickSelectedQuestionTypeIndex.value=index1
}
// 题目阅览区域的编辑按钮被点击
const handleEditQuestion=()=>{
  console.log('预览编辑按钮',clickSelectedQuestion.value);
  addingQuestion.value=clickSelectedQuestion.value
  isReview.value=false
  currentType.value=clickSelectedQuestion.value.questionType
  clickSelectedQuestionId.value=clickSelectedQuestion.value.questionId
}

const  isSelect = ref(true)
const selectedQuestions = ref(null)
// 所有试卷中的题目的ids
const currentPaperQuestionIds = computed(()=>{
  let ids = []
  paperQuestions.value.forEach(item=>{
    ids=ids.concat(item.questionList.map(q=>q.questionId))
  })
  return ids
})
//从题目中选择题目
const  handleSelectQuestion = (type) => {
  console.log(type,'选择题目的');
  if(type=='questionBank'){//从题库中选择题目
    isSelect.value=false
    console.log(currentPaperQuestionIds.value,'所有题目的ids');
  }
}
// 被选择的题目
watch(()=>selectedQuestions.value,(newVal)=>{
  console.log(newVal,'被选择的题目');
  if(newVal){
    // 添加题目
    const transformedQuestions = transformQuestions(newVal);
    console.log(transformedQuestions,'transformedQuestions');
    transformedQuestions.forEach(item => {
      // 判断是否存在相同的题型，存在则合并
      let flag = false;
      paperQuestions.value.forEach((typeItem, index1) => {
        if (typeItem.questionType === item.questionType) {
          flag = true;
          typeItem.count += item.count;
          typeItem.totalScore += item.totalScore;
          typeItem.questionList.push(...item.questionList);
          return; // 找到匹配
        }
      })
      if (!flag) {// 不存在则添加新的题型
        paperQuestions.value.push({
          questionType: item.questionType,
          count: item.count,
          totalScore: item.totalScore,
          desc: '题型说明',
          questionList: [...item.questionList],
        });
      }
    })
    console.log(paperQuestions.value,'添加题目后');
    //重新排序
    renumberAllQuestions()
    clickSelectedQuestion.value = 1 // 预览的题目编程下一个类目中的第一个

  }
})

// 处理会选择的题目 
function transformQuestions(questions) {
console.log('处理从题库中选择的题目',questions);
  const groups = {};
  // 按题型分组
  let  count = 1;
  questions.forEach(q => {
    if (!groups[q.questionType]) {
      groups[q.questionType] = {
        questionType: q.questionType,
        questionScore: 5,
        totalScore: 0,
        desc: '题型说明',
        questionList: [],
        count: 0
      };
    }
    groups[q.questionType].questionList.push({
      questionId: q.id,
      questionContent: q.title,
      questionScore: 5,
      questionDifficulty: q.difficulty,
      questionType: q.questionType,
      options:q.options?q.options:null,
      analysis: q.analysis?q.analysis:null,
      answer: q.answer?q.answer:null,
      currentQuestionNumber:count++

    });
  });
  
  // 计算总数和总分
  return Object.values(groups).map(group => {
    group.count = group.questionList.length;
    group.totalScore = group.count * group.questionScore;
    return group;
  });
}
</script >
<style lang="less" scoped>
/* 全局 CSS */;
.html-truncate {

  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap; /* 小屏幕单行截断 */
  p span{
     color:#6B7280 !important;
  }
}

@screen md {
  .html-truncate {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    white-space: nowrap; /* 中屏幕多行截断 */
  }
}

/* 强制内部所有元素为行内 */
.html-truncate > * {
  display: inline !important;
  white-space: nowrap !important;
}
</style>